#include <bits/stdc++.h>

using namespace std;

class Solution
{
public:
    vector<long long> findMaxSum(vector<int> &nums1, vector<int> &nums2, int k)
    {
        int n = nums1.size();
        vector<tuple<int, int, int>> sorted_list;
        for (int i = 0; i < n; ++i)
        {
            sorted_list.emplace_back(nums1[i], nums2[i], i);
        }
        sort(sorted_list.begin(), sorted_list.end(), [](const tuple<int, int, int> &a, const tuple<int, int, int> &b)
             { return get<0>(a) < get<0>(b); });

        vector<int> sorted_nums1(n);
        for (int i = 0; i < n; ++i)
        {
            sorted_nums1[i] = get<0>(sorted_list[i]);
        }

        vector<long long> prefix_max_sum;
        priority_queue<int, vector<int>, greater<int>> heap;
        long long sum_k = 0;

        for (int p = 0; p < n; ++p)
        {
            int num = get<1>(sorted_list[p]);
            heap.push(num);
            sum_k += (long long)num;

            if (heap.size() > k)
            {
                sum_k -= (long long)heap.top();
                heap.pop();
            }

            prefix_max_sum.push_back(sum_k);
        }

        vector<long long> answer(n, 0LL);

        for (int p = 0; p < n; ++p)
        {
            int target_val = get<0>(sorted_list[p]);
            auto pos = lower_bound(sorted_nums1.begin(), sorted_nums1.end(), target_val);
            int m_pos = distance(sorted_nums1.begin(), pos) - 1;
            int original_index = get<2>(sorted_list[p]);
            answer[original_index] = m_pos >= 0 ? prefix_max_sum[m_pos] : 0;
        }

        return answer;
    }
};
